package org.example.aidemo.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.example.aidemo.pojo.Location;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, String> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);

        // 使用StringRedisSerializer序列化键和值
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(new StringRedisSerializer());

        template.afterPropertiesSet();
        return template;
    }
    @Bean
    public RedisTemplate<String, Location> redisLocation(RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, Location> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);
        // 配置序列化方式
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new Jackson2JsonRedisSerializer<>(Location.class));
        return template;
    }
    @Bean
    public RedisTemplate<String, Location> locationRedisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, Location> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);

        // 配置序列化方式
        template.setKeySerializer(new StringRedisSerializer());

        // 创建并配置 ObjectMapper
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new JavaTimeModule()); // 注册 JavaTime 模块
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

        // 使用带 ObjectMapper 的构造函数创建 serializer
        Jackson2JsonRedisSerializer<Location> serializer = new Jackson2JsonRedisSerializer<>(objectMapper, Location.class);

        template.setValueSerializer(serializer);
        return template;
    }
}